package com.qh.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName QrZxing
 * @Description TODO
 * @Author keph@guahao.com
 * @Date 2019/7/30 23:26
 * @Version 1.0
 */
public class QrZxing {

    /**
     *      * 把string变成二维码然后转成Base64导出
     *      * @param string
     *      * @return
     *     
     */
    public static  String qrByBase64(String str) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置字符集编码类型
        hints.put(EncodeHintType.MARGIN, 1); //设置白边
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 800, 800, hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//输出二维码图片流
            try {
                ImageIO.write(image, "png", outputStream);
                return Base64.encodeBase64String(outputStream.toByteArray());
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (WriterException e1) {
// TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return null;
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);//0xFF000000黑；0xFFFFFFFF白
            }
        }
        return image;
    }
}
